package l1j.server.server.datatables;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import l1j.server.L1DatabaseFactory;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.templates.ItemMaker;
import l1j.server.server.utils.SQLUtil;
import l1j.server.server.utils.collections.Maps;

public class MakeItemTable {
	private static MakeItemTable _instance;

	public static MakeItemTable getInstance() {
		return _instance;
	}

	public static void initilize() {
		_instance = new MakeItemTable();
	}

	private MakeItemTable() {
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = L1DatabaseFactory.getInstance().getConnection();
			pstm = con
					.prepareStatement("SELECT * FROM x_item where box_type = ? or box_type = ?");
			pstm.setString(1, "個別機率");
			pstm.setString(2, "共用機率");
			rs = pstm.executeQuery();
			while (rs.next()) {
				int boxType = 0;
				if (rs.getString("box_type").equalsIgnoreCase("共用機率")) {
					boxType = 1;
				}
				ItemMaker itemMaker = new ItemMaker(boxType);
				String[] material_items = rs.getString("material_items").split(
						",");
				String[] material_counts = rs.getString("material_counts")
						.split(",");
				for (int i = 0; i < material_items.length; i++) {
					int itemId = Integer.parseInt(material_items[i]);
					if (itemId > 0) {
						itemMaker.addMaterial(itemId,
								Integer.parseInt(material_counts[i]));
					}

				}
				String[] get_chance = rs.getString("get_chance").split(",");
				String[] get_items = rs.getString("get_items").split(",");
				String[] get_counts = rs.getString("get_counts").split(",");
				for (int i = 0; i < get_chance.length; i++) {
					itemMaker.addGetItem(Integer.parseInt(get_items[i]),
							Integer.parseInt(get_counts[i]),
							Integer.parseInt(get_chance[i]));
				}

				_allItemMakers.put(rs.getInt("key_item"), itemMaker);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	private Map<Integer, ItemMaker> _allItemMakers = Maps.newMap();

	public boolean makeItem(int itemId, L1PcInstance pc) {
		boolean result = false;
		if (_allItemMakers.containsKey(itemId)) {
			result = true;
			ItemMaker im = _allItemMakers.get(itemId);
			if (im.checkMaterials(pc)) {
				im.consumeMaterials(pc);
				if (pc.getInventory().consumeItem(itemId, 1)) {
					im.getItem(pc);
				}
			}
		}
		return result;
	}
}
